/*
 * @Author: szx
 * @Date: 2022-01-06 14:08:19
 * @LastEditTime: 2022-01-06 14:24:21
 * @Description:
 * @FilePath: \leetcode\900-999\968\968.js
 */

function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}

/**
 * @param {TreeNode} root
 * @return {number}
 */
var minCameraCover = function (root) {
    let res = 0;
    // 0  是无覆盖， 1是有摄像头 ， 2是有覆盖
    const traversal = (node) => {
        if (node === null) {
            return 2;
        }
        // 后序遍历，就是为了处理叶子节点
        const left = traversal(node.left);
        const right = traversal(node.right);

        // 如果左右都有覆盖，那本节点就是无覆盖
        if (left == 2 && right == 2) return 0;

        // 如果左右有一个没覆盖，那么本节点就是摄像头
        if (left == 0 || right == 0) {
            res++;
            return 1;
        }

        // 如果左右有一个是摄像头，那么本节点就是有覆盖
        if (left == 1 || right == 1) return 2;

        return -1;
    };
    if (traversal(root) == 0) {
        res++;
    }
    return res;
};
